/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource.image;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ContentImage;
import com.blandware.atleap.model.core.ResourceData;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ImageForm;
import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.ImageUtil;
import com.blandware.atleap.webapp.util.core.ResourceTypesManager;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.apache.commons.validator.GenericValidator;

import javax.imageio.IIOImage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>Creates new content resource with type 'image'
 * </p>
 * <p><a href="CreateImageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.23 $ $Date: 2007/12/23 17:13:04 $
 * @struts.action path="/core/contentResource/image/create"
 * name="imageForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentResource-create"
 * @struts.action-forward name="inputForward"
 * path=".core.contentResource.image.create"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="true"
 * @struts.action-forward name="createContentResource"
 * path=".core.contentResource.create"
 * @struts.action-forward name="closeWindow"
 * path=".core.contentResource.closeWindow"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentResource/list.do"
 */
public final class CreateImageAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {
		ImageForm imageForm = (ImageForm) form;
        HttpSession session = request.getSession();
        boolean closeWindowAfterCreated = Boolean.TRUE.equals(session.getAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY));

        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);

        UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) session
                .getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
		if ( uploadContentResourceForm == null || uploadContentResourceForm.getFile() == null ) {
            // Maybe session was invalidated and after that user pressed 'back'
            // or 'cancel'?
            if (isBackPressed(request)) {
                session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
                saveToken(request);
                return mapping.findForward("createContentResource");
            }
            if ( isCancelled(request) ) {
                session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
                session.removeAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
                session.removeAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
                session.removeAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY);
                if (closeWindowAfterCreated) {
                    request.setAttribute("createdContentResource", Boolean.FALSE);
                    return mapping.findForward("closeWindow");
                }
                if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                    session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                    return new ActionForward(requestUrl, true);
                }
                return mapping.findForward("listContentResources");
            }
			if ( log.isWarnEnabled() ) {
				log.warn("Missing required attribute in session '" + WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY + "'");
			}
			ActionMessages errors = new ActionMessages();
			errors.add("missingResource", new ActionMessage("core.contentResource.errors.missingResource"));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		}
		FormFile formFile = uploadContentResourceForm.getFile();
		String fileName = formFile.getFileName();

        if (isBackPressed(request)) {
			if ( formFile != null ) {
				formFile.destroy();
			}
			session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
			saveToken(request);
			return mapping.findForward("createContentResource");
		}

		if ( isCancelled(request) ) {
			if ( formFile != null ) {
				formFile.destroy();
			}
			session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY);
            if (closeWindowAfterCreated) {
                request.setAttribute("createdContentResource", Boolean.FALSE);
                return mapping.findForward("closeWindow");
            }
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

		ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(
                session.getServletContext());
		String resourceType = resourceTypesManager.getResourceTypeByFileName(fileName);

		if ( !resourceType.equalsIgnoreCase(Constants.RESOURCE_TYPE_IMAGE) ) {
			throw new Exception("Resource must have " + Constants.RESOURCE_TYPE_IMAGE + " type");
		}

		ContentImage image = new ContentImage();
		WebappUtil.copyProperties(image, imageForm, request);
        WebappUtil.copyFieldValue(image.getDescription(), imageForm.getDescriptionMap());

        //setup uri
		String uri = Constants.RESOURCES_URI_PREFIX + imageForm.getUri();
		image.setUri(uri);

		String type = resourceTypesManager.getResourceTypeByFileName(fileName);
		image.setType(type);

		String mimeType = resourceTypesManager.getMimeTypeByFileName(fileName);

		byte[] imageData = formFile.getFileData();

		IIOImage source = ImageUtil.decodeImage(imageData, mimeType);

		if ( imageForm.isScale() ) {
			int maxWidth = Integer.parseInt(imageForm.getScaleWidth());
			int maxHeight = Integer.parseInt(imageForm.getScaleHeight());
			IIOImage scaled = ImageUtil.scaleToRectangle(source, maxWidth, maxHeight);
			try {
				imageData = ImageUtil.encodeImage(scaled, mimeType);
			} catch ( IllegalArgumentException ex ) {
				//cannot encode into original format, try to default
				mimeType = resourceTypesManager.getDefaultMimeType(type);
				imageData = ImageUtil.encodeImage(scaled, mimeType);
			}
            image.setWidth(new Integer(scaled.getRenderedImage().getWidth()));
            image.setHeight(new Integer(scaled.getRenderedImage().getHeight()));
            image.setSize(new Long(imageData.length));
		} else {
            image.setWidth(new Integer(source.getRenderedImage().getWidth()));
            image.setHeight(new Integer(source.getRenderedImage().getHeight()));
            image.setSize(new Long(imageData.length));
        }

		image.setMimeType(mimeType);

		ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
		try {
			Long contentResourceId = contentResourceManager.createContentImage(image, new ResourceData(imageData));

			//put into cache
			image = contentResourceManager.retrieveContentImage(contentResourceId);
			CacheUtil cacheUtil = CacheUtil.getInstance(request);
			CacheUtil.ResourceData rd = new CacheUtil.ResourceData(imageData, mimeType, null, image.getLastUpdatedDatetime().getTime());
			cacheUtil.putResourceInCache(rd, image.getUri());
		} catch ( BeanAlreadyExistsException e ) {
			// content resource already exists
			ActionMessages errors = new ActionMessages();
			errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		}

		if ( formFile != null ) {
			formFile.destroy();
		}
		session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
        session.removeAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
        session.removeAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
        session.removeAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY);

        if (closeWindowAfterCreated) {
            request.setAttribute("createdContentResource", Boolean.TRUE);
            request.setAttribute("createdContentResourceUri", image.getUri());
            return mapping.findForward("closeWindow");
        }
        if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
            session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
            return new ActionForward(requestUrl, true);
        }
        return mapping.findForward("listContentResources");

	}
}